package leetcode;

/**
 * Created by Ghost on 2014/11/12 0012.
 */
public class Rotate_List {
    private int getLen(ListNode head){
        ListNode tmp = head;
        int len = 0;
        while(tmp!=null){
            len++;
            tmp = tmp.next;
        }
        return len;
    }
    private ListNode moveRightByOne(ListNode head){
        ListNode cur = head;
        ListNode pre = head;
        while(cur.next!=null){
            pre = cur;
            cur = cur.next;
        }
        pre.next = null;
        cur.next = head;
        return cur;
    }
    public ListNode rotateRight(ListNode head, int n) {
        if(n==0)
            return head;
        if(head==null)
            return null;
        n = n%getLen(head);
        ListNode head1 = head;
        while(n>0){
            head1 = moveRightByOne(head);
            n--;
            head = head1;
        }
        return head1;
    }
    public static void main(String[] args){
        Rotate_List rotate_list = new Rotate_List();
        ListNode h = new ListNode(1);
        h.next = new ListNode(2);
        h.next.next = new ListNode(3);
//        h.next.next.next = new ListNode(4);

        ListNode head = rotate_list.rotateRight(h,0);
        while(head!=null){
            System.out.print(" "+head.val);
            head = head.next;
        }

    }
}
